//
//  CreateTribeViewController.m
//  yigou
//
//  Created by SunChao on 17/1/12.
//  Copyright © 2017年 hanyiwang. All rights reserved.
//

#import "CreateTribeViewController.h"
#import "ELCImagePickerController.h"
#import "QBImagePickerController.h"
#import "JCViewController.h"
#import "GCQiniuUploadManager.h"
#import "DFBigImageView.h"
typedef NS_OPTIONS(NSUInteger, SelectType) {
    SelectUserImg = 1,//用户头像
    SelectTribeImg= 2//部落头像
};

@interface CreateTribeViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate, ELCImagePickerControllerDelegate, QBImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UITextField *tribeName;
@property (weak, nonatomic) IBOutlet UITextField *tribeTitle;
@property (weak, nonatomic) IBOutlet UILabel *tribeDesc;
@property (nonatomic,strong)NSArray *labelArray;
@property (nonatomic,assign)NSUInteger selectType;
@property (strong, nonatomic) NSString *coverid;
@property (strong, nonatomic) NSString *userImgUrl;
@property (strong, nonatomic) NSString *tribeImgUrl;
@property (nonatomic,strong)DFBigImageView *userImg;
@property (nonatomic,strong)NSMutableArray *selectedArr;
@property (nonatomic,strong)NSMutableArray *dataSource;

@end

@implementation CreateTribeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.bgView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 300);
    self.tribeImgView.frame = self.bgView.frame;
    self.userImgView.backgroundColor = [UIColor clearColor];
    UIImageView *imgView = [[UIImageView alloc]initWithFrame:self.userImgView.frame];
    [self.userImgView setBackgroundColor:[UIColor colorWithPatternImage:imgView.image]];
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
    //设置点击次数和点击手指数
    tapGesture.numberOfTapsRequired = 1; //点击次数
    tapGesture.numberOfTouchesRequired = 1; //点击手指数
    self.userImgView.userInteractionEnabled = YES;
    [self.userImgView addGestureRecognizer:tapGesture];
    self.tribeImgView.alpha = 0.5;
    [self loadNetworkData];

}
//轻击手势触发方法
-(void)tapGesture:(id)sender
{
    self.selectType = SelectUserImg;
    [self clickAdd];
}
- (void)userImgAction:(UIButton *)button{
    self.selectType = SelectUserImg;
    [self clickAdd];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [ViewFactory setNavigationBlack:self];
    self.navigationItem.titleView = [ViewFactory makeNavigationTitle:@"创建部落"];
    
    UIBarButtonItem *backBtn = [ViewFactory makeNavigationBackWhite:self action:@selector(goPop)];
    self.navigationItem.leftBarButtonItem = backBtn;
    
    UIButton *button = [ViewFactory makeNavigationTextButtonWhite:@"创建"];
    [button addTarget:self action:@selector(goPublish) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.rightBarButtonItem = rightButton;
}

- (void)goPop {
    [self.view endEditing:YES];
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)leftBtnAction:(UIButton *)button{
    NSLog(@"本地选择部落背景");
    
    self.selectType = SelectTribeImg;
   
    [self clickAdd];
}

- (IBAction)rightBtnAction:(UIButton *)button{
    NSLog(@"随机选择部落背景");

    [self loadTribeImgView];
    
}
- (void)loadTribeImgView{
    
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = [NSString stringWithFormat:@"%@/hytribe/getRandomTribeBg", APIYIGOU];
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        NSDictionary *data = [dict objectForKey:@"data"];
        NSString *imgUrl = [data objectForKey:@"value"];
        [self.tribeImgView sd_setImageWithURL:[NSURL URLWithString:imgUrl] placeholderImage:[UIImage imageNamed:@""]];
    } error:^(YTKBaseRequest *request) {
        NSLog(@"error:%@",request);
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        
    }];
    
}
- (void)uploadTribeCover{
    NSData *coverdata = UIImageJPEGRepresentation(self.tribeImgView.image, HIGHSIZE);
    [[GCQiniuUploadManager sharedInstance] uploadData:coverdata progress:^(float percent) {
    } completion:^(NSError *error, NSString *link, NSInteger index) {
        if (link == nil) {
            [ViewFactory showErrorStrMsg:@"部落图片上传失败！"];
            [ViewFactory dismissLoading];
            return;
        }
        DYLog(@"upload index:%ld link:%@", index, link);
        if (link) {
            NSString *resurl = [NSString stringWithFormat:@"%@/%@", QNHOST, link];
            self.coverid = link;
            self.tribeImgUrl = resurl;
            [self loadReqest];
        }
    }];
}
//图片上传
- (void)uploadUserCover {
    NSData *coverdata = UIImageJPEGRepresentation(self.tribeImgView.image, NORMALSIZE);
    [[GCQiniuUploadManager sharedInstance] uploadData:coverdata progress:^(float percent) {
    } completion:^(NSError *error, NSString *link, NSInteger index) {
        if (link == nil) {
            [ViewFactory showErrorStrMsg:@"用户头像上传失败！"];
            [ViewFactory dismissLoading];
            return;
        }
        DYLog(@"upload index:%ld link:%@", index, link);
        if (link) {
            NSString *resurl = [NSString stringWithFormat:@"%@/%@", QNHOST, link];
            self.coverid = link;
            self.userImgUrl = resurl;
            [self uploadTribeCover];
        }
    }];
}
- (void)loadReqest{
    
    NSString *tribeTitle = [NSString stringWithFormat:@"%@",self.tribeTitle.text];
    NSString *tribeName = [NSString stringWithFormat:@"%@",self.tribeName.text];
    NSDictionary *textdict = @{
                                @"tribe_bg_img": self.tribeImgUrl,
                                @"tribe_desc": tribeTitle,
                                @"tribe_label": self.labelArray,
                                @"tribe_logo": self.userImgUrl,
                                @"tribe_name": tribeName
                                };
    
    NSString *urlStr = [NSString stringWithFormat:@"%@/hytribe/createTribe",APIYIGOU];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:[UserData usertoken] forHTTPHeaderField:@"Auth"];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:urlStr parameters:textdict success:^(NSURLSessionDataTask *task, id responseObject) {
        NSDictionary *dict = [NSDictionary changeType:(NSDictionary *)[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil]];
        if ([[dict valueForKey:@"code"] intValue] == 100) {
            [ViewFactory dismissLoading];
            [ViewFactory showSuccess:@"创建成功！"];
           
            [[NSNotificationCenter defaultCenter]postNotificationName:@"CreateMyTribe" object:nil];
            [self.navigationController popViewControllerAnimated:YES];
        }else if ([[dict valueForKey:@"code"]intValue] == 400){
            [ViewFactory showErrorStrMsg:@"创建失败！"];
             [ViewFactory showErrorStrMsg:[dict objectForKey:@"message"]];
        }
        DYLog(@"result:%@", dict.description);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error %ld",(long)error.code);
        [ViewFactory showErrorStrMsg:@"创建失败！"];
    }];
    
}

- (void)goPublish {
        if (self.tribeName.text==nil||self.tribeDesc.text== nil ||self.tribeTitle.text == nil||self.labelArray.count == 0||self.userImg.imageView.image == nil||self.tribeImgView.image == nil) {
            [ViewFactory showErrorStrMsg:@"资料不完整,不能创建部落"];
            return;
        }
    
    [ViewFactory showLoading];
    [self uploadUserCover];

    
}

- (void)clickAdd {
    [self.view endEditing:YES];
    UIAlertController* alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction* cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    UIAlertAction* takePhotoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self openCamera];
    }];
    
    UIAlertAction* choosePictureAction = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self choosePhoto];
    }];
    [alertVC addAction:cancleAction];
    [alertVC addAction:takePhotoAction];
    [alertVC addAction:choosePictureAction];
    
    [self presentViewController:alertVC animated:YES completion:nil];
}


#pragma mark-- 设置头像调用相机及选择照片相关代码
- (void)openCamera {
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    
    if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.sourceType = sourceType;
    
    [self presentViewController:picker animated:YES completion:^{
    }];
}

- (void)choosePhoto {
    NSInteger maxCount = 1;
    if (ISIOS7 || ISIOS8_0) {
        ELCImagePickerController *elcPicker = [ELCImagePickerController new];
        elcPicker.maximumImagesCount = maxCount;
        elcPicker.imagePickerDelegate = self;
        [self presentViewController:elcPicker animated:YES completion:nil];
    } else {
        QBImagePickerController *imagePickerController = [QBImagePickerController new];
        imagePickerController.assetCollectionSubtypes =@[
                                                         @(PHAssetCollectionSubtypeSmartAlbumUserLibrary), //相机胶卷
                                                         @(PHAssetCollectionSubtypeAlbumMyPhotoStream), //我的照片流
                                                         @(PHAssetCollectionSubtypeSmartAlbumPanoramas), //全景图
                                                         @(PHAssetCollectionSubtypeSmartAlbumBursts), //连拍模式拍摄的照片
                                                         @(PHAssetCollectionSubtypeSmartAlbumFavorites)
                                                         ];
        imagePickerController.delegate = self;
        imagePickerController.allowsMultipleSelection = YES;
        imagePickerController.mediaType = QBImagePickerMediaTypeImage;
        imagePickerController.maximumNumberOfSelection = maxCount;
        imagePickerController.showsNumberOfSelectedAssets = YES;
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
    
    [picker dismissViewControllerAnimated:YES completion:^{
        if (self.selectType == SelectUserImg) {
            self.userImg = [[DFBigImageView alloc]initWithFrame:CGRectMake((SCREEN_WIDTH-100)/2, 50, 100, 100)];
            self.userImg.imageView.image  = image;
            [self.userImg.imageButton addTarget:self action:@selector(userImgAction:) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview:self.userImg];
            self.userImg.imageView.layer.cornerRadius = 50;
            self.userImg.imageView.layer.masksToBounds = YES;
            [self.midView removeFromSuperview];
        }
        else if (self.selectType == SelectTribeImg){
            
            self.tribeImgView.image = image;
        }
        
    }];
}

- (void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info
{
    //TODO:changeToData
    [picker dismissViewControllerAnimated:YES completion:^{
        self.userImg = [[DFBigImageView alloc]initWithFrame:CGRectMake((SCREEN_WIDTH-100)/2, 50, 100, 100)];
        
        [self.tribeImgView addSubview:self.userImg];
    }];
}

- (void)elcImagePickerControllerDidCancel:(ELCImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{
        DYLog(@"cancl");
    }];
}

- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didFinishPickingAssets:(NSArray *)assets {
    NSUInteger count = assets.count;
    __block NSUInteger select = 0;
    PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];
    option.synchronous = YES;
    for (PHAsset *asset in assets) {
        [[PHCachingImageManager defaultManager]requestImageDataForAsset:asset options:option resultHandler:^(NSData * imageData, NSString * dataUTI, UIImageOrientation orientation, NSDictionary * info) {
            if (self.selectType == SelectUserImg) {
                self.userImg = [[DFBigImageView alloc]initWithFrame:CGRectMake((SCREEN_WIDTH-100)/2, 50, 100, 100)];
                self.userImg.imageView.image  = [UIImage imageWithData:imageData];
                self.userImg.imageView.layer.cornerRadius = 50;
                self.userImg.imageView.layer.masksToBounds = YES;
                [self.view addSubview:self.userImg];
               [self.userImg.imageButton addTarget:self action:@selector(userImgAction:) forControlEvents:UIControlEventTouchUpInside];
                [self.midView removeFromSuperview];
                [imagePickerController dismissViewControllerAnimated:YES completion:NULL];
                return;
                
            }
            else if (self.selectType == SelectTribeImg){
                
                self.tribeImgView.image = [UIImage imageWithData:imageData];
                [imagePickerController dismissViewControllerAnimated:YES completion:NULL];
                return;
                
            }
        }];
    }
}

- (void)qb_imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController {
    [imagePickerController dismissViewControllerAnimated:NO completion:NULL];
}
#pragma mark --选择标签
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"indexPath:%ld",indexPath.row);
    if (indexPath.row == 3) {
        //跳转选择标签页
        JCViewController *view = [[JCViewController alloc]init];
        [self.navigationController pushViewController:view animated:YES];
        view.dataSource = self.dataSource;
         view.selectedArr = self.selectedArr;
        [view returnText:^(NSString *showText) {
            self.dataSource = view.tagListView.tags;
            self.selectedArr = view.tagListView.selectedTags;
            if (view.tagListView.selectedTags.count != 0) {
                self.tribeDesc.textColor = [UIColor blackColor];
                self.tribeDesc.font = [UIFont systemFontOfSize:15];
                self.tribeDesc.text = showText;
                self.labelArray  = [self.tribeDesc.text componentsSeparatedByString:@","];
            }
        }];
    }
}

//数据请求
- (void)loadNetworkData {
    DYBaseRequest *request = [DYBaseRequest new];
    request.requestUrl = T_GETSYSTRIBELABEL;
    
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        NSArray *data = [dict objectForKey:@"data"];
        for (NSDictionary *tmpDic in data) {
            if ([tmpDic.allKeys containsObject:@"tribe_label"]) {
                NSString *str = [tmpDic objectForKey:@"tribe_label"];
                [self.dataSource addObject:str];
            }
        }
    } error:^(YTKBaseRequest *request) {
        
    } failure:^(YTKBaseRequest *request) {
        
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        
    }];
}

ARRAY_INIT(selectedArr)
ARRAY_INIT(dataSource)
@end
